package com.dstation.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dstation.domain.BulletChatInfo;
import com.dstation.domain.DamuInfo;
import com.dstation.domain.UserInfo;
import com.dstation.service.interf.IBulletChatService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Eastward
 * @date 2022/5/3 - 21:10
 */
@Controller
@RequestMapping("/bulletChat")
public class BulletChatController {

    @Autowired
    private IBulletChatService bulletChatService;

    @RequestMapping("/queryBulletChatInfo")
    @ResponseBody
    public String queryBulletChatInfo(Long videoId) throws JsonProcessingException {
        List<BulletChatInfo> list = bulletChatService.findBulletChatInfo(videoId);
        List<DamuInfo> damuInfos = new ArrayList<DamuInfo>();
        for (int i=0; i<list.size(); i++){
            DamuInfo damu = new DamuInfo();
            BulletChatInfo bulletChatInfo = list.get(i);
            damu.setText(bulletChatInfo.getBulletContent());
            damu.setTime(Integer.toString(bulletChatInfo.getBulletMoment()));
            damuInfos.add(damu);
        }
        String json = new ObjectMapper().writeValueAsString(damuInfos);
        return json;
    }

    @RequestMapping("/saveBulletChatInfo")
    @ResponseBody
    public String saveBulletChatInfo(@RequestBody Map<String, Object> map, HttpSession session){
        BulletChatInfo bulletChatInfo = new BulletChatInfo();
        // 将list中的数据转成json字符串
        String jsonObject = JSON.toJSONString(map.get("damuInfo"));
        //将json转成需要的对象
        DamuInfo damuInfo = (DamuInfo)JSONObject.parseObject(jsonObject, DamuInfo.class);
        bulletChatInfo.setBulletContent(damuInfo.getText());
        bulletChatInfo.setBulletMoment(Integer.parseInt(damuInfo.getTime()));
        bulletChatInfo.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        bulletChatInfo.setVideoId(Long.valueOf(map.get("videoId").toString()));
        bulletChatInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
        Boolean res = bulletChatService.addBulletChatInfo(bulletChatInfo);
        if (res){
            return "success";
        }else{
            return "error";
        }

    }
}
